package com.my.app.tools.ui;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.my.app.tools.core.business.CoreBusiness;
import com.my.app.tools.core.service.common.AppConfigService;
import com.my.app.tools.pojo.AppConstants;
import com.my.app.tools.pojo.vo.JTableColumnInfoVO;
import com.my.app.tools.util.AppThreadUtil;
import com.my.app.tools.util.LogUtil;
import org.apache.commons.collections.CollectionUtils;

import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

/**
 * 程序主界面
 *
 * @author guochaohui
 * @return
 * @date 2020-04-13 15:55
 */
public final class AppUiMain {

    public static int appWindowWidth = 640;
    public static int appWindowHeight = 480 + 25;

    private static JFrame jFrame;
    private static JTabbedPane mainTabbedPanel;

    private static JLabel loadingLabel;
    private static JPanel loadingPanel;
    private static JPanel allPanel;

    private static JPanel aboutPanel;
    private static JLabel aboutLabel;

    public static void initAppUi() {
        // 遮罩层加载提示
        loadingLabel = new JLabel("");
        loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
        loadingLabel.setVerticalAlignment(SwingConstants.CENTER);
        loadingLabel.setBounds(0, 0, appWindowWidth, appWindowHeight);
        loadingLabel.setFont(new Font(null, Font.PLAIN, 30));
        loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
        // 遮罩层
        loadingPanel = new JPanel(null);
        loadingPanel.setBounds(0, 0, appWindowWidth, appWindowHeight);
        loadingPanel.setVisible(false);
        loadingPanel.add(loadingLabel);
        // 帮助面板
        aboutPanel = new JPanel(new GridLayout(1, 1));
        aboutLabel = new JLabel("<html><body>" + Joiner.on("<br>").join(AppConstants.MY_APP_TITLE_ITEMS) + "</body></html>");
        aboutLabel.setFont(new Font(null, Font.PLAIN, 30));
        aboutLabel.setHorizontalAlignment(SwingConstants.CENTER);
        aboutPanel.add(aboutLabel);
        // 所有控件面板
        mainTabbedPanel = new JTabbedPane();
        mainTabbedPanel.setBounds(0, 0, appWindowWidth, appWindowHeight);
        mainTabbedPanel.addTab("关于软件", aboutPanel);
        mainTabbedPanel.addTab("截图识别", AppUiOcr.InitUi());
        mainTabbedPanel.addTab("文字翻译", AppUiTranslate.InitUi());
        mainTabbedPanel.addTab("随机个人信息", AppUiMakePeopleInfo.InitUi());
//        mainTabbedPanel.addTab("抓取企业信息", AppUiSpiderEnterpriseInfo.InitUi());
        // 所有面板
        allPanel = new JPanel(null);
        allPanel.setBounds(0, 0, appWindowWidth, appWindowHeight);
        allPanel.add(loadingPanel);
        allPanel.add(mainTabbedPanel);
        // 主窗口
        jFrame = new JFrame(Joiner.on(" | ").join(AppConstants.MY_APP_TITLE_ITEMS));
        jFrame.setSize(appWindowWidth, appWindowHeight);
        jFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        jFrame.setContentPane(allPanel);
        jFrame.setLocationRelativeTo(null);
        jFrame.setResizable(false);
        jFrame.setIconImage(AppConstants.getAppIcon());
        // 启动显示界面
        Boolean startShowMainUi = AppConfigService.readBooleanConfig("/app-config/show-main-ui");
        if (startShowMainUi == null || startShowMainUi) {
            showAppUi(0);
        }
        // 添加系统托盘
        addSystemTray();
    }

    private static void reloadAppConfig() {
        CoreBusiness.reloadAppConfig();
        AppUiMain.infoMsgBox("重新加载配置完毕！");
    }

    private static void addSystemTray() {
        try {
            if (!SystemTray.isSupported()) {
                LogUtil.error("当前系统不支持系统托盘");
                return;
            }
            // 获取当前平台的系统托盘
            SystemTray tray = SystemTray.getSystemTray();
            // 创建一个托盘图标
            TrayIcon trayIcon = new TrayIcon(AppConstants.getAppIcon(), Joiner.on(" | ").join(AppConstants.MY_APP_TITLE_ITEMS));
            trayIcon.setImageAutoSize(true);
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    // 显示菜单
                    JWindow popupMenuWindow = new JWindow();
                    JPopupMenu popupMenu = buildTrayPopupMenu();
                    popupMenu.addPopupMenuListener(new PopupMenuListener() {
                        @Override
                        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {

                        }

                        @Override
                        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {

                        }

                        @Override
                        public void popupMenuCanceled(PopupMenuEvent e) {
                            popupMenuWindow.dispose();
                        }
                    });
                    popupMenuWindow.setBounds(e.getX(), e.getY(), 1, 1);
                    popupMenuWindow.setVisible(true);
                    popupMenu.show(popupMenuWindow, 0, 0);
                }
            });
            // 添加系统托盘
            tray.add(trayIcon);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error(e.getMessage());
        }
    }

    private static JPopupMenu buildTrayPopupMenu() {
        JPopupMenu popupMenu = new JPopupMenu();
        // 显示程序
        JMenuItem openItem = new JMenuItem("显示程序");
        openItem.addActionListener(e1 -> {
            showAppUi();
        });
        popupMenu.add(openItem);
        // 立即执行截图识别
        JMenuItem ocrItem = new JMenuItem("立即截图识别");
        ocrItem.addActionListener(e1 -> {
            showAppUi(1);
            AppUiOcr.screenShot(true);
        });
        popupMenu.add(ocrItem);
        // 文字翻译
        JMenuItem translateItem = new JMenuItem("文字翻译");
        translateItem.addActionListener(e1 -> {
            showAppUi(2);
        });
        popupMenu.add(translateItem);
        // 随机个人信息
        JMenuItem peopleItem = new JMenuItem("随机个人信息");
        peopleItem.addActionListener(e1 -> {
            showAppUi(3);
        });
        popupMenu.add(peopleItem);
        // 抓取企业信息
        JMenuItem enterpriseItem = new JMenuItem("抓取企业信息");
        enterpriseItem.addActionListener(e1 -> {
            showAppUi(4);
        });
        // popupMenu.add(enterpriseItem);

        popupMenu.addSeparator();

        // 隐藏加载提示
        JMenuItem hideLoadingItem = new JMenuItem("隐藏加载提示");
        hideLoadingItem.addActionListener(e1 -> {
            hideLoading();
        });
        popupMenu.add(hideLoadingItem);

        // 重新加载配置
        JMenuItem reloadAppConfigItem = new JMenuItem("重新加载配置");
        reloadAppConfigItem.addActionListener(e1 -> {
            reloadAppConfig();
        });
        popupMenu.add(reloadAppConfigItem);

        popupMenu.addSeparator();
        // 退出程序
        JMenuItem exitItem = new JMenuItem("退出程序");
        exitItem.addActionListener(e1 -> {
            System.exit(0);
        });
        popupMenu.add(exitItem);
        return popupMenu;
    }

    /**
     * 异常弹窗
     *
     * @param message
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static void errorMsgBox(Object message) {
        JOptionPane.showMessageDialog(jFrame, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * 信息弹窗
     *
     * @param message
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static void infoMsgBox(Object message) {
        JOptionPane.showMessageDialog(jFrame, message, "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 清空table数据
     *
     * @param table
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static void clearTableData(JTable table) {
        setTableData(table, new Vector<>(), false);
    }

    /**
     * 设置table数据
     *
     * @param table
     * @param datas
     * @param append
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static void setTableData(JTable table, Vector<Vector> datas, boolean append) {
        JTableColumnInfoVO columnInfo = getTableColumnInfos(table);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        if (append) {
            Vector dataVector = model.getDataVector();
            datas.addAll(0, dataVector);
        }
        for (int i = 0; i < datas.size(); i++) {
            datas.get(i).set(0, i + 1);
        }
        model.setDataVector(datas, columnInfo.getTitles());
        setTableColumnWidth(table, columnInfo.getWidths());
    }

    /**
     * 设置table列宽
     *
     * @param table
     * @param widths
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static void setTableColumnWidth(JTable table, List<Integer> widths) {
        for (int i = 0; i < widths.size(); i++) {
            table.getColumnModel().getColumn(i).setWidth(widths.get(i));
            table.getColumnModel().getColumn(i).setMinWidth(widths.get(i));
            table.getColumnModel().getColumn(i).setMaxWidth(widths.get(i));
            table.getColumnModel().getColumn(i).setPreferredWidth(widths.get(i));
        }
    }

    /**
     * 获取table列信息
     *
     * @param table
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:17
     */
    public static JTableColumnInfoVO getTableColumnInfos(JTable table) {
        Vector<String> titles = new Vector<>();
        List<Integer> widths = Lists.newArrayList();
        Enumeration<TableColumn> columns = table.getColumnModel().getColumns();
        while (columns.hasMoreElements()) {
            TableColumn column = columns.nextElement();
            titles.add(String.valueOf(column.getHeaderValue()));
            widths.add(column.getWidth());
        }
        return new JTableColumnInfoVO(titles, widths);
    }

    /**
     * 显示加载提示
     *
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:18
     */
    public static void showLoading(String msg) {
        showLoading(msg, 10);
    }

    /**
     * 隐藏加载提示
     *
     * @return
     * @author guochaohui
     * @date 2020-03-24 19:15
     */
    public static void hideLoading() {
        loadingPanel.setVisible(false);
        mainTabbedPanel.setVisible(true);
    }

    /**
     * 显示加载提示
     *
     * @return
     * @author guochaohui
     * @date 2020-03-24 18:18
     */
    public static void showLoading(String msg, int hideTimeoutSeconds) {
        AppThreadUtil.INSTANCE.getExecutor().submit(() -> {
            try {
                loadingLabel.setText(msg);
                loadingPanel.setVisible(true);
                mainTabbedPanel.setVisible(false);
                Thread.sleep(hideTimeoutSeconds * 1000);
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.error(e.getMessage());
            } finally {
                hideLoading();
            }
        });
    }

    /**
     * 修改按钮可用状态
     *
     * @param enableButtons
     * @param disableButtons
     * @return
     * @author guochaohui
     * @date 2020-03-25 18:18
     */
    public static void changeButtonsEnable(List<JButton> enableButtons, List<JButton> disableButtons) {
        if (CollectionUtils.isNotEmpty(enableButtons)) {
            for (JButton button : enableButtons) {
                if (button == null) {
                    continue;
                }
                button.setEnabled(true);
            }
            ;
        }
        if (CollectionUtils.isNotEmpty(disableButtons)) {
            for (JButton button : disableButtons) {
                if (button == null) {
                    continue;
                }
                button.setEnabled(false);
            }
            ;
        }
    }

    /**
     * 隐藏app界面
     *
     * @return
     * @author guochaohui
     * @date 2020-04-07 18:39
     */
    public static void hideAppUi() {
        jFrame.setVisible(false);
    }

    /**
     * 显示app界面
     *
     * @return
     * @author guochaohui
     * @date 2020-04-07 18:39
     */
    public static void showAppUi() {
        jFrame.setVisible(true);
    }

    /**
     * 显示app界面
     *
     * @return
     * @author guochaohui
     * @date 2020-04-07 18:39
     */
    public static void showAppUi(int tabbedIndex) {
        jFrame.setVisible(true);
        mainTabbedPanel.setSelectedIndex(tabbedIndex);
    }

    /**
     * 点击table显示copy菜单
     *
     * @param e
     * @param table
     * @return
     * @author guochaohui
     * @date 2020-04-07 18:40
     */
    public static void clickTableShowCopyMenu(MouseEvent e, JTable table) {
        if (e.isMetaDown()) {
            return;
        }
        JPopupMenu popupMenu = new JPopupMenu();
        Vector<String> titles = AppUiMain.getTableColumnInfos(table).getTitles();
        for (int i = 0; i < titles.size(); i++) {
            String val = String.valueOf(table.getValueAt(table.getSelectedRow(), i));
            JMenuItem menuItem = new JMenuItem("复制 [ " + titles.get(i) + " ] [ " + val + " ]");
            menuItem.addActionListener(e1 -> {
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable transferable = new StringSelection(val);
                clipboard.setContents(transferable, null);
            });
            popupMenu.add(menuItem);
        }
        popupMenu.show(e.getComponent(), e.getX(), e.getY());
    }

}
